package com.dong.test;

import com.dong.dao.IUserDao;
import com.dong.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class Demo1 {
    private IUserDao userDao;
    private SqlSession session;
    private InputStream in;

    @Before
    public void init() throws Exception {
        //1.读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建 SqlSessionFactory 的构建者对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //3.使用构建者创建工厂对象 SqlSessionFactory
        SqlSessionFactory factory = builder.build(in);
        //4.使用 SqlSessionFactory 生产 SqlSession 对象
        session = factory.openSession();
        //5.使用 SqlSession 创建 dao 接口的代理对象
        userDao = session.getMapper(IUserDao.class);
    }

    @After
    public void after() throws Exception {
        //手动提交事务
        session.commit();
        //7.释放资源
        session.close();
        in.close();
    }

    @Test
    public void testFindAll() {

        //6.使用代理对象执行查询所有方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }

    }

    @Test
    public void testInsert() {
        User user = new User();
        user.setUsername("试试水");
        user.setPassword("783493");
        user.setGender("male");
        user.setEmail("632789@qq.com");
        user.setBirthDate(new Date());
        userDao.saveUser(user);
        System.out.println(user);
    }

    @Test
    public void testUpdate() {
        User user = new User();
        user.setUsername("jack");
        user.setPassword("666666");
        user.setId(20);
        userDao.updateUser(user);

    }

    @Test
    public void testDelete() {
        userDao.deleteUser(1);
    }

    @Test
    public void testFindById() {
        User user = userDao.findById(12);
        System.out.println(user);
    }

    @Test
    public void testFindByName() {
//        List<User> users = userDao.findByName("%通%");
        List<User> users = userDao.findByName("通");
        for (User user : users) {
            System.out.println(user);
        }
    }
    @Test
    public void testFindAllCount(){
        int count = userDao.findAllCount(19);
        System.out.println(count);
    }
}
